package com.cz.nongyetongv5.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.BeiJianDanWei;
import com.cz.nongyetongv5.bean.RecordHistory;
import com.cz.nongyetongv5.bean.Town;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.custom.wheelview.Utils;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.DialogUtil;
import com.cz.nongyetongv5.utils.GoHomeUtil;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;
import com.cz.nongyetongv5.utils.ImageUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@SuppressLint("NewApi")
public class JianGuanDuiXiangDetail extends Activity implements
		OnClickListener, AMapLocationListener {

	private BeiJianDanWei beiJianDanWei = null;

	/**
	 * 电话的布局
	 */
	private ViewGroup rlMobileLayout = null;

	/**
	 * 手机号码的布局
	 */
	private ViewGroup rlTelLayout = null;

	/**
	 * 发送短信的布局
	 */
	private ViewGroup llMessageLayout = null;
	/**
	 * 分割线
	 */
	private View vSplit = null;

	private ViewGroup btnBack = null;

	private ViewGroup btnNavgation = null;

	/**
	 * 高德地图的定位属性
	 */
	private LocationManagerProxy mAMapLocManager = null;
	/**
	 * 高德地图的定位信息对象
	 */
	private AMapLocation location = null;

	/**
	 * 等待导航资源载入的等待进度
	 */
	private CustomDialog waitNavgation = null;

	/**
	 * 监督检查统计信息点击的时候
	 */
	private ViewGroup btnJianDuJianChaCount;

	/**
	 * 产品检测统计信息点击的时候
	 */
	private ViewGroup btnChanPinJianCeCount;

	// 监督检查记录
	private List<RecordHistory> jianDuJianChaDatas = new ArrayList<RecordHistory>();

	// 监督检查不合格记录
	private List<RecordHistory> jianDuJianChaBuHeGeDatas = new ArrayList<RecordHistory>();

	// 产品检测记录
	private List<RecordHistory> chanPinJianCeDatas = new ArrayList<RecordHistory>();

	// 产品检测不合格记录
	private List<RecordHistory> chanPinJianCeBuHeGeDatas = new ArrayList<RecordHistory>();

	private User user;

	private ConfigUtil configUtil = null;
	/**
	 * 数据库工具类
	 */
	private DatabaseHelper db = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		// 查询出数据库对象
		db = new DatabaseHelper(this, CommonConstants.DBNAME, null,
				CommonConstants.DATABASE_VERSION);
		configUtil = new ConfigUtil(getResources());
		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);

		setContentView(R.layout.jianguanduixiang_detail);

		beiJianDanWei = (BeiJianDanWei) getIntent().getSerializableExtra(
				"beiJianDanWei");

		Log.d("rafedetail",beiJianDanWei.getCode()+":"+beiJianDanWei.getRegionName());
		TextView tvJianGuanDuiXiangName = (TextView) findViewById(R.id.tvJianGuanDuiXiangName);

		rlMobileLayout = (ViewGroup) findViewById(R.id.rlMobileLayout);

		rlMobileLayout.setOnClickListener(this);

		vSplit = findViewById(R.id.vSplit);

		rlTelLayout = (ViewGroup) findViewById(R.id.rlTelLayout);
		rlTelLayout.setOnClickListener(this);

		llMessageLayout = (ViewGroup) findViewById(R.id.llMessageLayout);
		llMessageLayout.setOnClickListener(this);

		btnBack = (ViewGroup) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(this);

		btnJianDuJianChaCount = (ViewGroup) findViewById(R.id.btnJianDuJianChaCount);
		btnJianDuJianChaCount.setOnClickListener(this);

		btnChanPinJianCeCount = (ViewGroup) findViewById(R.id.btnChanPinJianCeCount);
		btnChanPinJianCeCount.setOnClickListener(this);

		if (beiJianDanWei != null) {

			if (CharsetUtil.isNotNull(beiJianDanWei.getName())) {
				tvJianGuanDuiXiangName.setText(beiJianDanWei.getName());
			} else {
				tvJianGuanDuiXiangName.setText("未知");
			}

			TextView tvTel = (TextView) findViewById(R.id.tvTel);

			TextView tvMobile = (TextView) findViewById(R.id.tvMobile);

			if (CharsetUtil.isNotNull(beiJianDanWei.getMobile())
					&& CharsetUtil.isNotNull(beiJianDanWei.getTel())) {
				vSplit.setVisibility(View.VISIBLE);
				rlMobileLayout.setVisibility(View.VISIBLE);
				rlTelLayout.setVisibility(View.VISIBLE);

				tvMobile.setText("联系电话\u0020:\u0020" + beiJianDanWei.getTel());

				tvTel.setText("手机号码\u0020:\u0020" + beiJianDanWei.getMobile());

			} else {
				vSplit.setVisibility(View.GONE);

				if (CharsetUtil.isNotNull(beiJianDanWei.getTel())) {
					tvMobile.setText("联系电话\u0020:\u0020"
							+ beiJianDanWei.getTel());

					rlMobileLayout.setVisibility(View.VISIBLE);
					rlTelLayout.setVisibility(View.GONE);

				} else if (CharsetUtil.isNotNull(beiJianDanWei.getMobile())) {
					tvTel.setText("手机号码\u0020:\u0020"
							+ beiJianDanWei.getMobile());
					rlMobileLayout.setVisibility(View.GONE);
					rlTelLayout.setVisibility(View.VISIBLE);
				} else {
					rlMobileLayout.setVisibility(View.VISIBLE);
					rlMobileLayout.setClickable(false);
					tvMobile.setText("未填写电话信息");

					rlTelLayout.setVisibility(View.GONE);
				}

			}

			ViewGroup llElseInfoLayout = (ViewGroup) findViewById(R.id.llElseInfoLayout);

			TextView tvInfo1 = (TextView) llElseInfoLayout
					.findViewById(R.id.tvInfo1);

			String location = getIntent().getStringExtra("location");
			Town town=db.queryTownById(beiJianDanWei.getCode());
			if (town==null) {
				tvInfo1.setText("所属区域\u0020:\u0020未知");


			} else {


				String pathStr=town.getName();
				int sec=1;
				while(town!=null&&sec<100){
					town=db.queryTownById(town.getParent_code());
					if(town!=null)
						pathStr=town.getName()+">>"+pathStr;
					sec++;

				}tvInfo1.setText("所属区域\u0020:\u0020" + pathStr);
			}



			TextView tvAddress = (TextView) llElseInfoLayout
					.findViewById(R.id.tvAddress);

			String address = beiJianDanWei.getAddress();

			if (CharsetUtil.isNotNull(address)) {
				tvAddress
						.setText("地\u0020\u0020\u0020\u0020\u0020\u0020\u0020\u0020址\u0020:\u0020"
								+ address);
			} else {
				tvAddress
						.setText("地\u0020\u0020\u0020\u0020\u0020\u0020\u0020\u0020址\u0020:\u0020未知");
			}

			TextView tvInfo3 = (TextView) llElseInfoLayout
					.findViewById(R.id.tvInfo3);

			Integer kind = beiJianDanWei.getKind();

			if (kind != null && kind > 0) {

				tvInfo3.setText("对象性质\u0020:\u0020"
						+ beiJianDanWei.getKindStr());

			} else {
				tvInfo3.setText("对象性质\u0020:\u0020未知");
			}


			TextView tvInfo4 = (TextView) llElseInfoLayout
					.findViewById(R.id.tvInfo4);

			String categoryStr = beiJianDanWei.getCategoryStr();

			tvInfo4.setText("企业类别\u0020:\u0020" + categoryStr);

			TextView tvInfo5 = (TextView) findViewById(R.id.tvCharge);

			String charge = beiJianDanWei.getCharge();

			if (CharsetUtil.isNotNull(charge)) {
				tvInfo5.setText("负\u0020\u0020责\u0020\u0020人\u0020:\u0020"
						+ charge);
			} else {
				tvInfo5.setText("负\u0020\u0020责\u0020\u0020人\u0020:\u0020未知");
			}

			btnNavgation = (ViewGroup) findViewById(R.id.btnNavgation);
			btnNavgation.setOnClickListener(this);

			if (configUtil.gis()) {
				if (beiJianDanWei!=null&&
						beiJianDanWei.getLatitude()!=null&&beiJianDanWei.getLatitude() > 0
						&& beiJianDanWei.getLongitude() > 0) {

					btnNavgation.setVisibility(View.VISIBLE);
					btnNavgation.setClickable(true);

				} else {
					btnNavgation.setVisibility(View.INVISIBLE);

					btnNavgation.setClickable(false);
				}
			} else {
				btnNavgation.setVisibility(View.INVISIBLE);
			}

		}

		/**
		 * 警示信息的布局
		 */
		final ViewGroup vgJingShiXinXi = (ViewGroup) findViewById(R.id.llJingShi);

		/*
		 * 警示信息的布局不包括标题
		 */
		final ViewGroup vgJingShiItemLayout = (ViewGroup) findViewById(R.id.llJingShiItemLayout);

		// 清理布局
		vgJingShiItemLayout.removeAllViews();

		/*
		 * 隐藏警示信息外部的布局
		 */
		vgJingShiXinXi.setVisibility(View.GONE);

		user = (User) getIntent().getSerializableExtra("user");

		// 存在网络则去搜寻数据
		if (CommonConstants.isNetworkConnected(JianGuanDuiXiangDetail.this)) {

			new AsyncTask<Integer, Integer, Integer>() {

				private CustomDialog customDialog = null;

				private Integer responseCodeRet;

				private String responseBodyRet;

				@Override
				protected Integer doInBackground(Integer... params) {

					String validateUsername = new ConfigUtil(getResources())
							.getRestUsername();

					String validatePassword = new ConfigUtil(getResources())
							.getRestPassword();

					// 监督检查统计
					String jianDuJianChaCountUrl = new ConfigUtil(
							getResources()).getPreHttpUrl()
							+ getString(R.string.jiandujiancha_count)
							+ beiJianDanWei.getId() + "/this_year/1";

					if (configUtil.duchaxuncha()) {

						jianDuJianChaCountUrl = new ConfigUtil(getResources())
								.getPreHttpUrl()
								+ getString(R.string.duchaxuncha_count)
								+ beiJianDanWei.getId() + "/this_year/1";
					}

					// 产品检测统计
					String chanPinJianCeCountUrl = new ConfigUtil(
							getResources()).getPreHttpUrl()
							+ getString(R.string.chanpinjiance_count)
							+ beiJianDanWei.getId() + "/this_year/1";

					HttpUtils jianDuJianChaHttpUtil = new HttpUtils();
					//
					// 监督检查数据
					jianDuJianChaHttpUtil
							.setOnRequestExecuted(new OnRequestExecuted() {

								@Override
								public void onRequestExecuted(int responseCode,
															  String responseBody) {

									if (responseCode == HttpUtils.SUCCESS) {
										try {
											JSONObject jsonObject = new JSONObject(
													responseBody);

											String status = jsonObject
													.getString("status");

											if ("1".equals(status)
													|| "true".equals(status)) {

												JSONArray resultJson = jsonObject
														.getJSONArray("result");

												for (int i = 0; i < resultJson
														.length(); i++) {

													JSONObject resultItemJson = resultJson
															.getJSONObject(i);

													String id = resultItemJson
															.getString("id");

													String date = resultItemJson
															.getString("date");

													// 被检单位的名字
													String enterprise_names = resultItemJson
															.getString("enterprise_names");

													// 检查单位的名字
													String department_names = resultItemJson
															.getString("department_names");

													// 检查人员的名字
													String inspector_names = resultItemJson
															.getString("inspector_names");

													// 检查结果
													Integer result_final = resultItemJson
															.getInt("result_final");

													// 图片
													String photo = resultItemJson
															.getString("photo");

													RecordHistory jianDuJianCha = new RecordHistory();

													jianDuJianCha.setTime(date);

													jianDuJianCha
															.setBeiJianName(enterprise_names);

													jianDuJianCha
															.setJianGuanName(department_names);

													jianDuJianCha
															.setRenYuan(inspector_names);

													jianDuJianCha
															.setResult(result_final);

													jianDuJianCha
															.setImageUrl(photo);

													jianDuJianCha.setId(id);

													// 监督检查/监督检查，筛选出不合格的
													/*
													 * 1 ： 合格 2 : 基本合格 3 : 不合格
													 */
													if (result_final == 3) {
														jianDuJianChaBuHeGeDatas
																.add(jianDuJianCha);
													} else {
														jianDuJianChaDatas
																.add(jianDuJianCha);
													}

												}

											}

										} catch (JSONException e) {

											Log.d("error~", e.getMessage());

											e.printStackTrace();
										}

									}

								}
							});

					Log.d("urldebug", "监管对象-监督检查/督查巡查 地址 : "
							+ jianDuJianChaCountUrl);

					jianDuJianChaHttpUtil.sendRequest(jianDuJianChaCountUrl,
							null, "GET", "UTF-8", validateUsername,
							validatePassword, user);

					HttpUtils chanPinJianCeHttpUtil = new HttpUtils();

					chanPinJianCeHttpUtil
							.setOnRequestExecuted(new OnRequestExecuted() {

								@Override
								public void onRequestExecuted(int responseCode,
															  String responseBody) {

									if (responseCode == HttpUtils.SUCCESS) {

										try {
											JSONObject jsonObject = new JSONObject(
													responseBody);

											String status = jsonObject
													.getString("status");

											if ("1".equals(status)
													|| "true".equals(status)) {

												JSONArray resultJson = jsonObject
														.getJSONArray("result");

												for (int i = 0; i < resultJson
														.length(); i++) {

													JSONObject resultItemJson = resultJson
															.getJSONObject(i);

													String id = resultItemJson
															.getString("id");

													// 时间
													String date = resultItemJson
															.getString("date");

													// 检测单位
													String detector_name = resultItemJson
															.getString("detector_name");

													// 抽样单位
													String enterprise_name = resultItemJson
															.getString("enterprise_name");

													// 抽样结果
													Integer record_results = resultItemJson
															.getInt("record_results");

													// 抽样人员
													String worker_names = resultItemJson
															.getString("worker_names");

													// 产品名称
													String record_names = resultItemJson
															.getString("record_names");

													String photo = resultItemJson
															.getString("photo");

													RecordHistory chanPinJianCe = new RecordHistory();

													chanPinJianCe.setTime(date);

													chanPinJianCe
															.setBeiJianName(enterprise_name);

													chanPinJianCe
															.setJianGuanName(detector_name);

													chanPinJianCe
															.setRenYuan(worker_names);

													chanPinJianCe
															.setResult(record_results);

													chanPinJianCe
															.setImageUrl(photo);

													chanPinJianCe
															.setChanPin(record_names);

													chanPinJianCe.setId(id);

													// chanPinJianCe
													// .setFromJianGuanDuiXinag(true);

													// 2 产品检测不合格，筛选出不合格的
													if (record_results == 2) {
														chanPinJianCeBuHeGeDatas
																.add(chanPinJianCe);
													} else {

														chanPinJianCeDatas
																.add(chanPinJianCe);
													}

												}

											}

										} catch (JSONException e) {
											Log.d("error~", e.getMessage());
											e.printStackTrace();
										}

									}

								}
							});

					chanPinJianCeHttpUtil.sendRequest(chanPinJianCeCountUrl,
							null, "GET", "UTF-8", validateUsername,
							validatePassword, user);

					HttpUtils jingShiXinXiHttpUtil = new HttpUtils();

					String jingShiXinXiUrl = new ConfigUtil(getResources())
							.getPreHttpUrl()
							+ getString(R.string.jingshixinxi_has_count_url)
							+ beiJianDanWei.getId();

					jingShiXinXiHttpUtil
							.setOnRequestExecuted(new OnRequestExecuted() {

								@Override
								public void onRequestExecuted(int responseCode,
															  String responseBody) {

									responseCodeRet = responseCode;

									responseBodyRet = responseBody;

								}
							});

					jingShiXinXiHttpUtil.sendRequest(jingShiXinXiUrl, null,
							"GET", "UTF-8", validateUsername, validatePassword,
							user);

					return null;
				}

				@Override
				protected void onPreExecute() {

					customDialog = new CustomDialog(JianGuanDuiXiangDetail.this);

					customDialog.setCanceledOnTouchOutside(true);

					customDialog.setMessage("正在加载统计信息...");

					customDialog.showWait();

					super.onPreExecute();
				}

				@Override
				protected void onPostExecute(Integer result) {

					if (responseCodeRet == HttpUtils.SUCCESS) {

						final OnClickListener clickListener = new OnClickListener() {

							@Override
							public void onClick(View v) {

								String warning = (String) v.getTag();

								Intent intent = new Intent(
										JianGuanDuiXiangDetail.this,
										JingShiXinXiActivity.class);

								intent.putExtra("warning", warning);

								intent.putExtra("user", user);

								intent.putExtra("id", beiJianDanWei.getId());

								startActivity(intent);

							}
						};

						try {
							JSONObject jsonObject = new JSONObject(
									responseBodyRet);

							String status = jsonObject.getString("status");

							if ("1".equals(status) || "true".equals(status)) {

								JSONObject resultJson = jsonObject
										.getJSONObject("result");

								// 证书已经过期
								int cert_expireds = resultJson
										.getInt("cert_expireds");

								// 证书将过期
								int cert_upcoming = resultJson
										.getInt("cert_upcoming");

								// 产地已过期
								int origin_expireds = resultJson
										.getInt("origin_expireds");

								// 产地信息将过期
								int origin_upcoming = resultJson
										.getInt("origin_upcoming");

								List<Integer> counts = new ArrayList<Integer>();

								counts.add(cert_expireds);

								counts.add(cert_upcoming);

								counts.add(origin_expireds);

								counts.add(origin_upcoming);

								for (int i = 0; i < counts.size(); i++) {

									int count = counts.get(i);

									if (count > 0) {

										if (vgJingShiXinXi.getVisibility() == View.GONE) {
											vgJingShiXinXi
													.setVisibility(View.VISIBLE);
										}

										RelativeLayout rlLayout = new RelativeLayout(
												JianGuanDuiXiangDetail.this);

										rlLayout.setMinimumHeight(Utils
												.dip2px(JianGuanDuiXiangDetail.this,
														50));

										rlLayout.setBackgroundResource(R.drawable.btn_back_pressed);

										rlLayout.setClickable(true);

										rlLayout.setPadding(
												0,
												0,
												0,
												Utils.dip2px(
														JianGuanDuiXiangDetail.this,
														5));

										/*
										 * 增加文字标题
										 */
										TextView tvTitle = new TextView(
												JianGuanDuiXiangDetail.this);

										switch (i) {
											case 0:

												rlLayout.setTag("1");
												rlLayout.setOnClickListener(clickListener);

												tvTitle.setText("三品一标\u0020已过期");

												// 设置字体大小
												tvTitle.setTextSize(
														TypedValue.COMPLEX_UNIT_SP,
														18);

												tvTitle.setTextColor(Color
														.parseColor("#ffff0000"));

												break;

											case 1:

												rlLayout.setTag("3");
												rlLayout.setOnClickListener(clickListener);

												tvTitle.setText("三品一标\u0020将到期");

												// 设置字体大小
												tvTitle.setTextSize(
														TypedValue.COMPLEX_UNIT_SP,
														18);

												tvTitle.setTextColor(Color
														.parseColor("#F4C82D"));

												break;

											case 2:

												rlLayout.setTag("2");
												rlLayout.setOnClickListener(clickListener);

												tvTitle.setText("产地信息\u0020已过期");

												// 设置字体大小
												tvTitle.setTextSize(
														TypedValue.COMPLEX_UNIT_SP,
														18);

												tvTitle.setTextColor(Color
														.parseColor("#ffff0000"));

												break;

											case 3:

												rlLayout.setTag("4");
												rlLayout.setOnClickListener(clickListener);

												tvTitle.setText("产地信息\u0020将到期");

												// 设置字体大小
												tvTitle.setTextSize(
														TypedValue.COMPLEX_UNIT_SP,
														18);

												tvTitle.setTextColor(Color
														.parseColor("#F4C82D"));

												break;

										}

										LayoutParams tvTitleLayoutParams = new LayoutParams(
												LayoutParams.WRAP_CONTENT,
												LayoutParams.WRAP_CONTENT);

										tvTitleLayoutParams.leftMargin = Utils
												.dip2px(JianGuanDuiXiangDetail.this,
														5);

										// 设置居中
										tvTitleLayoutParams.addRule(
												RelativeLayout.CENTER_VERTICAL,
												RelativeLayout.TRUE);

										rlLayout.addView(tvTitle,
												tvTitleLayoutParams);

										/*
										 * 图片的布局
										 */
										ImageView ivImage = new ImageView(
												JianGuanDuiXiangDetail.this);
										ivImage.setImageResource(R.drawable.jiandujiancha_icon_more);
										ivImage.setClickable(false);

										LayoutParams ivImageLayoutParam = new LayoutParams(
												Utils.dip2px(
														JianGuanDuiXiangDetail.this,
														20),
												Utils.dip2px(
														JianGuanDuiXiangDetail.this,
														20));

										ivImageLayoutParam
												.addRule(
														RelativeLayout.ALIGN_PARENT_RIGHT,
														RelativeLayout.TRUE);
										// 设置居中
										ivImageLayoutParam.addRule(
												RelativeLayout.CENTER_VERTICAL,
												RelativeLayout.TRUE);

										ivImageLayoutParam.rightMargin = Utils
												.dip2px(JianGuanDuiXiangDetail.this,
														8);

										rlLayout.addView(ivImage,
												ivImageLayoutParam);

										vgJingShiItemLayout
												.addView(
														rlLayout,
														new LayoutParams(
																LayoutParams.MATCH_PARENT,
																LayoutParams.WRAP_CONTENT));

										View view = new View(
												JianGuanDuiXiangDetail.this);
										view.setBackgroundColor(Color
												.parseColor("#C4C3C1"));

										vgJingShiItemLayout
												.addView(
														view,
														new LayoutParams(
																LayoutParams.MATCH_PARENT,
																1));

									}

								}

							}

						} catch (JSONException e) {
						}

					}

					if (customDialog != null) {

						customDialog.dismiss();

						TextView tvJianDuJianChaCount = (TextView) findViewById(
								R.id.llCount).findViewById(R.id.tvInfo);

						String title = configUtil.getConfig() == 1 ? "督查巡查"
								: "监督检查";

						String jianDuJianChaTxt = title
								+ "&nbsp;:&nbsp;共"
								+ (jianDuJianChaDatas.size() + jianDuJianChaBuHeGeDatas
								.size()) + "次";

						if (jianDuJianChaBuHeGeDatas.size() > 0) {

							jianDuJianChaTxt += "&nbsp;(<font color=\"red\">不合格"
									+ jianDuJianChaBuHeGeDatas.size()
									+ "次</font>)";
						}

						tvJianDuJianChaCount.setText(Html
								.fromHtml(jianDuJianChaTxt));

						TextView tvChanPinJianCeCount = (TextView) findViewById(
								R.id.llCount).findViewById(R.id.tvInfo2);

						String chanPinJianCeText = "产品检测&nbsp;:&nbsp;共"
								+ (chanPinJianCeDatas.size() + chanPinJianCeBuHeGeDatas
								.size()) + "次";

						if (chanPinJianCeBuHeGeDatas.size() > 0) {

							chanPinJianCeText += "&nbsp;(<font color=\"red\">不合格"
									+ chanPinJianCeBuHeGeDatas.size()
									+ "次</font>)" + "";
						}

						tvChanPinJianCeCount.setText(Html
								.fromHtml(chanPinJianCeText));

					}

				};

			}.execute();

		} else {
			// 不存在网络则隐藏统计信息的外部布局
			findViewById(R.id.llCount).setVisibility(View.GONE);
		}


		loadRightTitle();
	}


	/**
	 * 加载去主页的按钮
	 */
	public void loadRightTitle() {

		ViewGroup btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		View view = GoHomeUtil.createPopView(getApplicationContext(),
				new String[] { "主页" });

		// 弹出更多的菜单
		final PopupWindow pop = new PopupWindow(view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(new BitmapDrawable());

		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);

		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);

		final Button btn01 = (Button) pop.getContentView().findViewWithTag(
				"btn0");

		OnClickListener menuOnClick = new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (v == btn01) {
					GoHomeUtil.goHome(getApplicationContext());
				}
			}
		};

		btn01.setOnClickListener(menuOnClick);

		btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		btnMeanMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (pop.isShowing()) {
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				} else {
					// 显示窗口
					pop.showAsDropDown(v);
				}

			}
		});

	}
	@Override
	protected void onRestart() {

		super.onRestart();
	}

	/**
	 * 清理高德地图的资源
	 */
	@Override
	protected void onDestroy() {

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		if (mAMapLocManager != null) {
			mAMapLocManager.removeUpdates(this);
			mAMapLocManager.destory();
		}
		mAMapLocManager = null;
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();

		/*
		 * 初始化高德地图的定位对象
		 */
		mAMapLocManager = LocationManagerProxy.getInstance(this);
		/*
		 * mAMapLocManager.setGpsEnable(false);//
		 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true Location
		 * API定位采用GPS和网络混合定位方式
		 * ，第一个参数是定位provider，第二个参数时间最短是5000毫秒，第三个参数距离间隔单位是米，第四个参数是定位监听者
		 */
		mAMapLocManager.requestLocationUpdates(
				LocationProviderProxy.AMapNetwork, 1500, 10, this);

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mAMapLocManager != null) {
			mAMapLocManager.removeUpdates(this);
			mAMapLocManager.destory();
		}
		mAMapLocManager = null;

	}

	@Override
	public void onClick(View v) {

		// 监督检查的统计详细
		if (v == btnJianDuJianChaCount) {

			if ((jianDuJianChaDatas.size() + jianDuJianChaBuHeGeDatas.size()) > 0) {

				Intent intent = new Intent(this, TongJiXinXiActivity.class);

				intent.putExtra("data", (ArrayList) jianDuJianChaDatas);

				intent.putExtra("user", user);

				intent.putExtra("buhegedata",
						(ArrayList) jianDuJianChaBuHeGeDatas);

				String title = configUtil.getConfig() == 1 ? "督查巡查" : "监督检查";

				intent.putExtra("title", title + "统计");

				startActivity(intent);

			}

		}

		// 产品检测的统计详细
		if (v == btnChanPinJianCeCount) {

			if ((chanPinJianCeDatas.size() + chanPinJianCeBuHeGeDatas.size()) > 0) {

				Intent intent = new Intent(this, TongJiXinXiActivity.class);

				intent.putExtra("data", (ArrayList) chanPinJianCeDatas);
				intent.putExtra("user", user);

				intent.putExtra("buhegedata",
						(ArrayList) chanPinJianCeBuHeGeDatas);

				intent.putExtra("title", "产品检测统计");

				startActivity(intent);
			}

		}

		// 拨打电话
		if (v == rlMobileLayout) {
			Intent intent_to_call = new Intent(Intent.ACTION_DIAL,
					Uri.parse("tel:" + beiJianDanWei.getTel()));

			startActivity(intent_to_call);

		}

		// 拨打手机
		if (v == rlTelLayout) {
			Intent intent_to_call = new Intent(Intent.ACTION_DIAL,
					Uri.parse("tel:" + beiJianDanWei.getMobile()));

			startActivity(intent_to_call);
		}

		// 发送短信
		if (v == llMessageLayout) {
			Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"
					+ beiJianDanWei.getMobile()));
			startActivity(intent);
		}

		// 退出
		if (v == btnBack) {
			finish();
		}

		if (v == btnNavgation) {

			if (location != null) {

				double latiude = location.getLatitude();

				double longitude = location.getLongitude();

				String[] pointArr = gd_to_bd(latiude, longitude).split(",");

				int lat = (int) (Double.parseDouble(pointArr[1]) * 1E6);

				int lon = (int) (Double.parseDouble(pointArr[0]) * 1E6);
//
//				GeoPoint pt1 = new GeoPoint(lat, lon);
//
//				// 终点
//				lat = (int) (beiJianDanWei.getLatitude() * 1E6);
//				lon = (int) (beiJianDanWei.getLongitude() * 1E6);

//				GeoPoint pt2 = new GeoPoint(lat, lon);
//
//				// 构建 导航参数
//				final NaviPara para = new NaviPara();
//				para.startPoint = pt1;
//
//				para.startName = "从这里开始";
//
//				para.endPoint = pt2;
//
//				para.endName = "到这里结束";

				try {
					// 调起百度地图客户端导航功能,参数this为Activity。
//					BaiduMapNavigation.openBaiduMapNavi(para,
//							JianGuanDuiXiangDetail.this);
//
//					location = null;

				} catch (BaiduMapAppNotSupportNaviException ex) {

					String errMessage = ex.getMessage().trim();

					final File apkFile = new File(
							ImageUtil.getThisAppDataFile(), "baiduditu.apk");

					if ("BaiduMap app is not installed".equals(errMessage)) {

						final CustomDialog customDialog = new CustomDialog(
								JianGuanDuiXiangDetail.this);

						customDialog.setMessage("未下载地图组件!");

						customDialog.setCancleTxt("网页导航");

						customDialog
								.setOnCancleClickListener(new OnClickListener() {

									@Override
									public void onClick(View v) {
//										BaiduMapNavigation.openWebBaiduMapNavi(
//												para,
//												JianGuanDuiXiangDetail.this);
//
//										customDialog.dismiss();
									}
								});

						customDialog
								.setOnActionClickListener(new OnClickListener() {

									@Override
									public void onClick(View v) {

										customDialog.dismiss();

										if ("安装".equals(customDialog
												.getActionTxt())) {

											installApk(apkFile);

										} else {

											final CustomDialog downloadWait = new CustomDialog(
													JianGuanDuiXiangDetail.this);
											downloadWait
													.setMessage("正在下载百度地图...");
											downloadWait.showWait();

											final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

											String apkUrl = "http://czfood360.cn/update/apps/bd.apk";

											DownloadManager.Request request = new DownloadManager.Request(
													Uri.parse(apkUrl));

											request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
													| DownloadManager.Request.NETWORK_WIFI);

											request.setTitle("百度地图");
											request.setDescription("正在为您下载百度地图..");
											//
											request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

											request.setMimeType("application/cn.trinea.download.file");

											final File file = ImageUtil
													.getThisAppDataFile();

											request.setDestinationUri(Uri
													.fromFile(new File(file,
															"baiduditu.apk")));

											request.setVisibleInDownloadsUi(true);

											final long downloadId = downloadManager
													.enqueue(request);

											IntentFilter filter = new IntentFilter(
													DownloadManager.ACTION_DOWNLOAD_COMPLETE);

											BroadcastReceiver receiver = new BroadcastReceiver() {
												@Override
												public void onReceive(
														Context context,
														Intent intent) {
													long reference = intent
															.getLongExtra(
																	DownloadManager.EXTRA_DOWNLOAD_ID,
																	-1);
													if (downloadId == reference) {

														downloadWait.dismiss();

														installApk(apkFile);
													}
												}
											};
											registerReceiver(receiver, filter);

											IntentFilter clickItemFilter = new IntentFilter(
													DownloadManager.ACTION_NOTIFICATION_CLICKED);

											BroadcastReceiver clickItemReceiver = new BroadcastReceiver() {
												@Override
												public void onReceive(
														Context context,
														Intent intent) {
													String extraID = DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS;
													long[] references = intent
															.getLongArrayExtra(extraID);
													for (long reference : references)
														if (reference == downloadId) {

															Toast.makeText(
																	getApplicationContext(),
																	"下载完成后会自动打开...",
																	Toast.LENGTH_SHORT)
																	.show();

														}
												}
											};

											registerReceiver(clickItemReceiver,
													clickItemFilter);

										}
									}
								});

						if (apkFile.exists()) {
							customDialog.setActionTxt("安装");
						} else {
							customDialog.setActionTxt("下载");
						}

						customDialog.show();

					}

				}
				location = null;

			} else {

				waitNavgation = new CustomDialog(JianGuanDuiXiangDetail.this);
				waitNavgation.setMessage("正在加载导航资源...");

				waitNavgation.showWait();

			}

		}

	}

	/**
	 * 当地址改变的时候,此方法已经废弃
	 */
	@Override
	public void onLocationChanged(Location location) {
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

	/**
	 * 当地址改变的时候
	 */
	@Override
	public void onLocationChanged(AMapLocation location) {
		if (location != null) {

			this.location = location;

			if (waitNavgation != null && waitNavgation.isShowing()) {

				onClick(btnNavgation);

				waitNavgation.dismiss();

			}

			/*
			 * 高德地图的定位案例 Double geoLat = location.getLatitude(); Double geoLng =
			 * location.getLongitude(); String cityCode = ""; String desc = "";
			 * Bundle locBundle = location.getExtras(); if (locBundle != null) {
			 * cityCode = locBundle.getString("citycode"); desc =
			 * locBundle.getString("desc"); }
			 *
			 * String str = ("定位成功:(" + geoLng + "," + geoLat + ")" +
			 * "\n精    度    :" + location.getAccuracy() + "米" + "\n定位方式:" +
			 * location.getProvider() + "\n定位时间:" + "\n城市编码:" + cityCode +
			 * "\n位置描述:" + desc + "\n省:" + location.getProvince() + "\n市:" +
			 * location.getCity() + "\n区(县):" + location.getDistrict() +
			 * "\n区域编码:" + location .getAdCode());
			 *
			 * Toast.makeText(PaiZhaoActivity.this, str,
			 * Toast.LENGTH_SHORT).show();
			 */
		}
	}

	private String gd_to_bd(double gg_lat, double gg_lon) {

		double bd_lat, bd_lon;

		double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

		double x = gg_lon, y = gg_lat;

		double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);

		double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);

		bd_lon = z * Math.cos(theta) + 0.0065;

		bd_lat = z * Math.sin(theta) + 0.006;

		return bd_lon + "," + bd_lat;
	}

	private void installApk(File file) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		startActivityForResult(intent, RESULT_CANCELED);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_CANCELED) {

			if (appIsExists("com.baidu.BaiduMap")) {

				onClick(btnNavgation);

			} else {
				DialogUtil.showMessageDialog("安装失败..", null,
						JianGuanDuiXiangDetail.this);

			}

		}
	}

	private boolean appIsExists(String packageName) {

		try {
			getPackageManager().getApplicationInfo(packageName,
					PackageManager.GET_UNINSTALLED_PACKAGES);

			return true;
		} catch (NameNotFoundException e) {
			return false;
		}

	}

}
